package com.example.liaoshanqing

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileWriter
import java.io.IOException
fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)

class MainActivity : AppCompatActivity() {
    private lateinit var num1EditText: EditText
    private lateinit var num2EditText: EditText
    private lateinit var resultEditText: EditText
    private lateinit var addButton: Button
    private lateinit var subtractButton: Button
    private lateinit var multiplyButton: Button
    private lateinit var divideButton: Button
    private lateinit var historyButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitle("廖山清2022110318")
        setContentView(R.layout.activity_main)

        num1EditText = findViewById(R.id.num1)
        num2EditText = findViewById(R.id.num2)
        resultEditText = findViewById(R.id.result)
        addButton = findViewById(R.id.add)
        subtractButton = findViewById(R.id.subtract)
        multiplyButton = findViewById(R.id.multiply)
        divideButton = findViewById(R.id.divide)
        historyButton = findViewById(R.id.history)

        addButton.setOnClickListener {
            performOperation("+")
        }
        subtractButton.setOnClickListener {
            performOperation("-")
        }
        multiplyButton.setOnClickListener {
            performOperation("*")
        }
        divideButton.setOnClickListener {
            performOperation("/")
        }
        historyButton.setOnClickListener {
            val intent = Intent(this, HistoryActivity::class.java)
            startActivity(intent)
        }
    }

    private fun performOperation(operation: String) {
        val num1 = num1EditText.text.toString().toDoubleOrNull()
        val num2 = num2EditText.text.toString().toDoubleOrNull()
        if (num1 != null && num2 != null) {
            val result = when (operation) {
                "+" -> num1 + num2
                "-" -> num1 - num2
                "*" -> num1 * num2
                "/" -> if (num2 != 0.0) num1 / num2 else 0.0
                else -> 0.0
            }
            resultEditText.text = result.toString().toEditable()
            saveHistory("$num1 $operation $num2 = $result")
        }
    }

    private fun saveHistory(history: String) {
        try {
            val file = File(filesDir, "history.txt")
            val writer = FileWriter(file, true)
            writer.append(history).append("\n")
            writer.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}